import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import type { RequestOptionsInit } from 'umi-request';
import { currentUser as queryCurrentUser } from './services/user/api';
import { notification } from 'antd';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/account/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.username,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

// 拦截请求，加入 jwt token
const jwtRequestInterceptor = (url: string, options: RequestOptionsInit) => {
  const token = window.localStorage.getItem('jwt-token');
  if (!token) {
    history.push('/account/login');
  }

  const authHeader = { Authorization: 'Bearer ' + token };
  return {
    url: `${url}`,
    options: { ...options, interceptors: true, headers: authHeader },
  };
};

// 拦截响应，判断是否要迁移到 login 页面
const jwtResponseInterceptor = (response: Response) => {
  try {
    if (response.status === 401) {
      window.localStorage.clear();
      history.push('/account/login');
    }
  } catch (err) {
    console.log(err);
  }

  return response;
};

// 统一的错误处理
const errorHandler = (error: { response: any }) => {
  const { response } = error;

  if (response && response.status) {
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: '权限不足',
    });
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }

  return response;
};

export const request: RequestConfig = {
  errorHandler,
  requestInterceptors: [jwtRequestInterceptor],
  responseInterceptors: [jwtResponseInterceptor],
};
